package com.ynny.chapter04.controller;

import com.ynny.chapter04.dao.UserDao;
import com.ynny.chapter04.dao.UserDaoImpl;
import com.ynny.chapter04.entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {

        String userName = request.getParameter("userName");

        String password = request.getParameter("pwd");

        //非空校验

        if (userName == null || userName.equals("") ||
                password == null || password.equals("")) {
          //保存错误信息 到request域中
            request.setAttribute("msg", "用户名或密码不能为空");

            request.getRequestDispatcher("/login.jsp")
                    .forward(request, response);
        }else {

            //校验用户名是否存在
            //根据用户名去查询 当前用户是否存在
            UserDao userDao = new UserDaoImpl();

            User user = userDao.selectUserByUserName(userName);
            if (user == null){

                request.setAttribute("msg", "用户名不存在,请先注册账号!");
                request.getRequestDispatcher("/login.jsp")
                        .forward(request, response);

            }else {

                //校验密码是否正确
                //通过用户名和密码 去查询用户
                User loginUser = userDao.selectUserByUserNameAndPassword(userName, password);
                if (loginUser == null){
                    request.setAttribute("msg", "密码错误");
                    request.getRequestDispatcher("/login.jsp")
                            .forward(request, response);
                }else {

                    //登录成功

                   List<User> users = userDao.selectAllUsers();

                   request.getSession().setAttribute("users", users);


                    //重定向跳转到主页
                    response.sendRedirect("/chapter04/index.jsp");

                }


            }

        }

    }
}
